package com.doumuxie.interceptors;

import com.doumuxie.annotations.CheckToken;
import com.doumuxie.service.UserService;
import com.doumuxie.util.ResponseUtil;
import com.doumuxie.util.ResultUtil;
import com.doumuxie.util.SysCode;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author doumuxie https://gitee.com/doumuxie/
 * @version 1.0
 * @date 2020/5/21 21:16
 * @description CheckToken 注解拦截器 （用于校验用户是否已经登录 并 进行授权）
 **/
@Configuration
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CheckToken checkToken;
        if (handler instanceof HandlerMethod) {
            checkToken = ((HandlerMethod) handler).getMethodAnnotation(CheckToken.class);
        } else {
            return true;
        }
        // 检查是否需要token登录
        if (checkToken != null) {
            String token = request.getHeader("token");
            logger.info("==============检测到token注解，进行拦截token:[{}]==============", token);
            if (StringUtils.isBlank(token)) {
                ResponseUtil.sendResponse(response, ResultUtil.error(SysCode.Token.ERROR));
                return false;
            }
            // 检测token是否过期
            boolean isLogin = userService.userInfo(token).getSuccess();
            if (!isLogin) {
                ResponseUtil.sendResponse(response, ResultUtil.error(SysCode.Token.ERROR));
                return false;
            }
        }
        return true;
    }

//    /**
//     * 根据jwt缓存查询是否存存在某权限
//     *
//     * @param userDto jwt user
//     * @param value   要校验的auth
//     * @return true / false
//     */
//    private boolean hasAuth(JwtUserDto userDto, String value) {
//        if (StringUtils.isBlank(value)) {
//            return false;
//        }
//        // 分割多个权限
//        String[] split = value.split(",");
//        // 获取所有权限
//        Set<String> auths = userDto.getAuths();
//        for (String auth : split) {
//            if (!auths.contains(auth)) {
//                // 有权限不存在
//                return false;
//            }
//        }
//        return true;
//    }


}
